package topic

import (
	"context"

	"mall/common/ctxdatax"
	"mall/common/mqueuex"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type RemoveTopicLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRemoveTopicLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RemoveTopicLogic {
	return &RemoveTopicLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RemoveTopicLogic) RemoveTopic(req *types.RemoveTopicReq) (resp *types.BaseDataInfo, err error) {
	if len(req.Ids) == 0 {
		return &types.BaseDataInfo{
			Status:  "ok",
			Message: "",
		}, nil
	}

	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	_, err = l.svcCtx.ForumRpc.RemoveTopic(l.ctx, &forumclient.RemoveTopicReq{
		Ids:       req.Ids,
		UpdatedBy: pointy.GetPointer(userId),
	})
	if err != nil {
		return nil, err
	}

	var userMeta []*userclient.UserMetaInfo
	userMeta = append(userMeta, &userclient.UserMetaInfo{
		Key:   pointy.GetPointer(mqueuex.UserStatisticForumQuestionNew), // "_asked_question_new_status"
		Value: pointy.GetPointer("-1"),
	})
	l.svcCtx.UserRpc.SetUserMeta(l.ctx, &userclient.SetUserMetaReq{
		UserId:   pointy.GetPointer(userId),
		MetaKey:  pointy.GetPointer(mqueuex.UserStatisticForumQuestionCount), // "_asked_question_count"
		Incr:     pointy.GetPointer(int32(-1)),
		UserMeta: userMeta,
	})

	return &types.BaseDataInfo{
		Status:  "ok",
		Message: "删除成功",
	}, nil
}
